package net.pluce.nxt.network.impl;

import java.io.DataInputStream;
import java.io.EOFException;

import net.pluce.nxt.network.EventWatcher;
import net.pluce.nxt.network.RobotConnection;
import net.pluce.nxt.network.RobotListener;

/**
 * This implementation takes stream bytes as integers three by three and uses them to form a DistanceMessage or a DirectionMessage, sent to the listeners.
 * @author Pluce
 */
public class ThreeIntEventWatcher implements EventWatcher {
	
	private RobotConnection connection;
	private Throwable errorFlag = null;
	
	public ThreeIntEventWatcher(RobotConnection connection) {
		this.connection = connection;
	}
	
	public ThreeIntEventWatcher() {
	}
	
	/* (non-Javadoc)
	 * @see net.pluce.nxt.network.impl.EventWatcherInterface#getErrorFlag()
	 */
	@Override
	public Throwable getErrorFlag(){
		return errorFlag;
	}
	
	/* (non-Javadoc)
	 * @see net.pluce.nxt.network.impl.EventWatcherInterface#run()
	 */
	@Override
	public void run(){
		DataInputStream dis = new DataInputStream(connection.getInputStream());
		boolean closed = false;
		int msgType, msg1param, msg2param;
		Message buffer;
		int read;
		while(!closed){
			read = 0;
			try{
				msgType = dis.readInt();
				read++;
				msg1param = dis.readInt();
				read++;
				msg2param = dis.readInt();
				read++;
				buffer = new Message(msgType,msg1param,msg2param);
				if(msgType == 1) sendDistance(buffer);
				if(msgType == 2) sendDirection(buffer);
			} catch(Throwable e){
				closed = true;
				if(!((e instanceof EOFException) && read == 3))
					errorFlag = e;
			}
		}
	}

	private void sendDirection(Message msg) {
		for(RobotListener listener: connection.getListeners()){
			listener.directionReceived(msg);
		}
	}

	private void sendDistance(Message msg) {
		for(RobotListener listener: connection.getListeners()){
			listener.distanceReceived(msg);
		}
	}

	@Override
	public void setRobotConnection(RobotConnection robotConnection) {
		this.connection = robotConnection;		
	}
}
